package cn.fanyamin.web.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.fanyamin.domain.Book;

public class BookNoDbDao implements BookDao {
	private static List<Book> books = new ArrayList<Book>(5);
	
	static {
		Book book1 = new Book();
		book1.setBookID(1);
		book1.setBookName("Design Pattern");
		book1.setBookSN("tp111");
		book1.setBorrowLogID(111);
		book1.setCategoryID(111);
		
		Book book2 = new Book();
		book2.setBookID(2);
		book2.setBookName("Code Complete");
		book2.setBookSN("tp222");
		book2.setBorrowLogID(111);
		book2.setCategoryID(111);
		
		books.add(book1);
		books.add(book2);
	}
	
	public List<Book> getBooks() {
		return books;
	}

	
	public Book getBook(Integer id) {
		 Book book = null;
		 Iterator<Book> iter = books.iterator();
	        while (iter.hasNext()) {
	            book = (Book)iter.next();
	            if (book.getBookID()==id) {
	                break;
	            }
	        }
	        return book;
	}

	
	public void update(Book book) {
		Integer id = book.getBookID();
        for (int i = 0; i < books.size(); i++) {
            Book tempEmp = (Book)books.get(i);
            if (tempEmp.getBookID()==id) {
                 books.set(i, book);
                break;
            }
        }

	}

	
	public void insert(Book book) {
		int lastId = 0;
        Iterator<Book> iter = books.iterator();
        while (iter.hasNext()) {
            Book temp = (Book)iter.next();
            if (temp.getBookID() > lastId) {
                lastId = temp.getBookID();
            }
        }
        book.setBookID(lastId + 1);
        books.add(book);

	}

	
	public void delete(Integer id) {
		for (int i = 0; i < books.size(); i++) {
            Book tmpBook = (Book)books.get(i);
            if (tmpBook.getBookID()==id) {
                books.remove(i);
                break;
            }
        }

	}

}
